//
// Created by renyi on 16/6/18.
//
#include "Json_parse.h"

int device_parse(char* json, char* device_id, char* device_name, char* device_sn){

    int i_return = 1;
    json_object *result_object = json_tokener_parse(json);
    if(is_error(result_object) ) //正确
    {
        printf("json_parse error\n");
        return -1;
    }

    json_object *result_object1 = NULL;
    if (!json_object_object_get_ex(result_object, "result", &result_object))
    {
        return 0;
    }

    result_object =  json_object_array_get_idx(result_object, 1);

    if (json_object_object_get_ex(result_object, "device_id", &result_object1))
    {
        strcpy(device_id, json_object_to_json_string(result_object1));
        i_return = 2;
    }

    if (json_object_object_get_ex(result_object, "device_name", &result_object1))
    {
        strcpy(device_name, json_object_to_json_string(result_object1));
        i_return = 2;
    }

    if (json_object_object_get_ex(result_object, "device_sn", &result_object1))
    {
        strcpy(device_sn, json_object_to_json_string(result_object1));
        i_return = 2;
    }

    //device_id =json_object_to_json_string(result_object1);
    //printf("-----------device_id method ---------------------------\n");
    //printf("%s\n", json_object_to_json_string(result_object1));
    //printf("-----------device_id method---------------------------\n");

    json_object_put(result_object);
    json_object_put(result_object1);
    return i_return;
}

int password_parse(char* json, char* password){
    //char test[1000];
    //sprintf(test, "{\"jsonrpc\":\"2.0\",\"id\":0,\"method\":\"call\",\"params\":[\"\",\"netcfg\",\"set_device_discovery\",{\"device_id\":\"%s\",\"device_name\":\"%s\",\"device_password\":\"12345678\"}]}", "device_id", "device_name");

    json_object *result_object = json_tokener_parse(json);
    if(is_error(result_object) ) //正确
    {
        printf("password json_parse error\n");
        return -1;
    }

    json_object *result_object1 = NULL;
    if (!json_object_object_get_ex(result_object, "params", &result_object))
    {
        return 0;
    }

    result_object =  json_object_array_get_idx(result_object, 3);

    if (json_object_object_get_ex(result_object, "device_password", &result_object1))
    {
        strcpy(password, json_object_to_json_string(result_object1));
    }

    return 1;

//    printf("-----------test method ---------------------------\n");
//    printf("%s\n", json_object_to_json_string(result_object1));
//    printf("-----------test method---------------------------\n");

}
